// Team 1 Project - Palo Alto Bicycle Club
// Author: Vern McGeorge
// Class: COIN 71
// Filename: group_rides.js
// Date Created: 04 March 09
// Purpose:
// 		Support Group Rides by implementing the Date Picker, Query Rides, and Ride List components

// On page load, remove href elements from ride links, hook in javascript callbacks, and initialize
// the ride listing startingr from today. If javascript is disabled, the href attributes will not be
// removed and hopefully, the app will degrade well.
function initGroupRides() {
	var findLink = document.getElementById("findARide");
	var postLink = document.getElementById("postARide");
	var homeLink = document.getElementById("headerTitle");
	var routeLink = document.getElementById("goToRouteLib");
	var newsLink = document.getElementById("goToNewsletter");
	var announceLink = document.getElementById("goToAnnouncements");
	
	findLink.href = "javascript:void(0)";
	postLink.href = "javascript:void(0)";
	homeLink.href = "javascript:void(0)";
	routeLink.href = "javascript:void(0)";
	newsLink.href = "javascript:void(0)";
	announceLink.href = "javascript:void(0)";
	
	findLink.onclick = queryRidesFromToday;
	postLink.onclick = postAGroupRide;
	homeLink.onclick = queryRidesFromToday;
	routeLink.onclick = goToRouteLibrary;
	newsLink.onclick = goToNewsletters;
	announceLink.onclick = goToAnnouncements;
	
	queryRidesFromToday();      // initialize the ride listing.
}
jQuery.event.add( window, "load", initGroupRides );
/*jQuery.event.add( window, "load", loadWeather );
jQuery.event.add( window, "load", loadRetail );
*/

// Fill the right column with rides starting from today.
function queryRidesFromToday() {
	SELECTED_DATE = new Date();
	queryRides(SELECTED_DATE);
}

// ************** Ajaxy Page Load functions ******************* //

// Load the add_ride partial with contentLoader ...
function postAGroupRide() {
	var url = "add_ride.php";
	var contentLoader = new net.ContentLoader(url, formLoaded);
}

// load the route library partial
function goToRouteLibrary() {
    var url = "routelibrary_partial.php";
    var contentLoader = new net.ContentLoader(url, formLoaded);
}

// Load the newsletter partial with contentLoader ...
function goToNewsletters() {
	var url = "newsletters_partial.php";
	var contentLoader = new net.ContentLoader(url, simpleFormLoad);
}

// Load the announcements partial with contentLoader ...
function goToAnnouncements() {
	var url = "announcements_partial.php";
	var contentLoader = new net.ContentLoader(url, announcementsLoaded);
}

/* --- attempt to get widgets loaded via ajax... 
function loadWeather() {
    var url = 'http://netweather.accuweather.com/adcbin/netweather_v2/netweatherV2.asp?partner=netweather&tStyle=whteYell&logo=1&zipcode=94303&lang=eng&size=12&theme=black&metric=0&target=_self';
    var contentLoader = new net.ContentLoader(url, formLoaded);
}

function loadRetail() {
    var url = "http://ws.amazon.com/widgets/q?ServiceVersion=20070822&MarketPlace=US&ID=V20070822/US/widgetsamazon-20/8002/c0940409-6ddf-4c02-8ba0-e7ea0e8f0cfd";
    var contentLoader = new net.ContentLoader(url, storeLoaded);
}

function weatherLoaded() {
	document.getElementById('weather').innerHTML = this.req.responseText;
}

function storeLoaded() {
	document.getElementById('retailLink').innerHTML = this.req.responseText;
}
*/

// form-loading callback for pages that do no require any additional initialization
function simpleFormLoad() {
    var newHTML = this.req.responseText;
	var contentArea = document.getElementById('contentArea');
	contentArea.innerHTML = newHTML;
}

// ... and stuff it into the right column. Then set up the date picker and time picker.
function formLoaded() {
	var newHTML = this.req.responseText;
	var contentArea = document.getElementById('contentArea');
	contentArea.innerHTML = newHTML;
	// For popup date picker in the "Post a Ride" form.
	$('#popupDatepicker').datepick({closeAtTop : false});
	// For popup time picker (timepickr plugin) in the "Post a Ride" form.
		$('#timepickr').timepickr({convention:12});
		// temporary fix..
		$('.ui-dropslide ol:eq(0) li:first').mouseover();
		// apply theme
		$('#timepickr').next().addClass('dark');
}


// form-loading callback to initialize Route Library containing arguments for dataTable initialization
function routelibraryLoaded() {
    var newHTML = this.req.responseText;
	var contentArea = document.getElementById('contentArea');
	contentArea.innerHTML = newHTML;
	
	oTable = $('#routeList').dataTable( {
                    "bPaginate" : false,
                    "bSort" : false,
                    "bFilter" : false,
                    "bStateSave" : true
				} );


                $("thead select").change( function () {
                    /* Filter on the column (the index) of this element */
                    oTable.fnFilter( this.value, $("thead select").index(this)+1 );
                })
                
                
	/*$('#routeList').dataTable( {"bPaginate" : true, "bSort" : false, "bFilter" : false, "bStateSave" : true} );
	$("thead select").change( function () {
                Filter on the column (the index) of this element
                oTable.fnFilter( this.value, $("thead select").index(this)+1 );
            }) */
}


// displays the announcements page inside "contentArea", then adds the announcements stored in "announcements.xml"
function announcementsLoaded() {
    var newHTML = this.req.responseText;
	var contentArea = document.getElementById('contentArea');
	contentArea.innerHTML = newHTML;

    var contentLoader = new net.ContentLoader("announcements.xml", buildList); // load old announcements
}



// When a date is selected, query the database for rides starting from that date.
function queryRides(date) {
	SELECTED_DATE = new Date(date);
	sendSelectQuery(SELECTED_DATE);
}


// Once data is returned from the database, construct well formatted HTML and stuff it into the right column.
function updateRideListing() { // JSON version

    var rides = RESULTS;
	var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
	var mos = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
	var contentArea = document.getElementById('contentArea');
	
	var newHTML = '<div id="GRSchedule">';   // locate Group Ride info in unique div for styling.
	newHTML += '<h2>Upcoming Group Rides</h2>';
	var priorDay = null;
	for (var i = 0; i < rides.length; i++) {
		
		var rideDay = dateStringToDate(rides[i].date);		// makes a new Date object from MySQL date formatted string
		var hdr = null;
		if (null == priorDay) {
			hdr = getDateHeaderString(rideDay);
		} else {
			if (rideDay.toDateString() != priorDay.toDateString()) { // .toDateString compares "dates" WITHOUT time, more reliable than valueOf()
				hdr = getDateHeaderString(rideDay);				
			}
		}		
		priorDay = rideDay;		
		if (hdr) {
			newHTML += "<h3>" + hdr + "</h3>";
		}
		var description = sampleString( rides[i].description, 80 ); // sampleString function modified 3.17.09 by Tyler
		
		newHTML += '<div class="ridelisting">' +                   
                    '<h4><span class="ride_time">' + formatTimeString(rides[i].time) + '</span><span class="ride_title">' + rides[i].title + '</span><span class="details_link"><a onclick="createDetailsUI('+ i + ')" href="javascript:void(0);">see Map</a></span><span class="ride_rating">' + rides[i].category + ' / ' + rides[i].hilliness + ' / ' + rides[i].mileage + '</span></h4>' +
                    '<a onclick="createDetailsUI('+ i + ')" href="javascript:void(0);"><img src="_images/PABikeClubLogo.jpg" width="41" height="57" alt="Bike Club Logo" /></a>' +
                    '<div class="grleftcol">Start Point:</div><div class="grrightcol">'+ rides[i].start_point + '</div>' +
                    '<div class="grleftcol">Leader:</div><div class="grrightcol">'+ rides[i].leader + '</div>' +
                    '<div class="grleftcol">Description:</div><div class="grrightcol">'+ description + '</div>' +
                    '</div>';
	}
	
	newHTML += '</div>';  // close GRSchedule div
	
	contentArea.innerHTML = newHTML; // Display list.	
	
	
	// Console to display info about results.
	// written by Vern
	// added by Tyler, 3.19.09
	var statusArea = document.createElement('div');
	statusArea.setAttribute('id', 'statusArea');	
	contentArea.appendChild( statusArea );
	
	// status logger (by Vern) added 3.19.09 by Tyler
    if (0 == rides.length) {
            showStatus(Status_Warning, "No group rides found.");
        } else if (1 == rides.length) {
            showStatus(Status_Success, "1 group ride found.");
        } else {
            showStatus(Status_Success, rides.length + " group rides found.");
        }	
}





// Construct a human friendly date header string.
function getDateHeaderString(rideDay) {
	var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
	var mos = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
	var day = days[rideDay.getDay()];
	var mo = mos[rideDay.getMonth()];
	var date = rideDay.getDate();
	var year = rideDay.getFullYear();
	return day + ", " + mo + " " + date;
}

// takes a mysql date-format string "YYYY-MM-DD" and returns a date object for that day
function dateStringToDate(dateString) {
	var newDate = new Date();
	var dateParts = dateString.split("-");
	newDate.setFullYear(dateParts[0], dateParts[1]-1, dateParts[2]);
	return newDate;
}

// formats a mysql time-format string "hh:mm:ss" to conventional time display
function formatTimeString(timeString) {
    var parts = timeString.split(":");
    var hr = parseInt( eval( parts[0] % 12 ));
    var min = ( parseInt(parts[1]) != 0 ) ? parseInt(parts[1]) : "00";
    var mark = ( parseInt(parts[0])/12 > 1 ) ? "pm" : "am"; 
    
    return ""+hr+":"+min+" "+mark;    
}

// shortens "string" to "numChar" characters and replaces "<br />" with " / "
function sampleString (string, numChar) {

    var cleanStr = string.replace( "<br />", " / ");    
    if (cleanStr.length > numChar ) {
        return cleanStr.slice(0, numChar) + "...";
    } else { 
        return cleanStr; 
    }    
}





/*
********************** Announcements Page function *****************
*/

function validateAnnouncement()
	{
		var errorMessage = "";
		var titleValue = document.getElementById('title').value;
		var authorValue = document.getElementById('author').value;		
		var msgValue = document.getElementById('message').value;
		//title, author, message should not be empty
		if (titleValue.length < 1 || authorValue.length < 1 || msgValue.length < 1 )
		{
			errorMessage = "All fields should have a value to post an announcement.\n";
		}
		
		//message
		if(msgValue.length > 300)
		{
			errorMessage += 'Message length should be no greater than 300 characters.';
		}	
		if (errorMessage.length > 0)
		{
			alert (errorMessage);
			return false;
		}
	}